#include "../head/server.h"
#include "../head/md5.h"

// salt
void generate_salt(char *salt, int length)
{
	const char charset[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
	srand(time(NULL));
	salt[0] = '$';
	salt[1] = '6';
	salt[2] = '$';
	salt[19] = '$';
	for (int i = 3; i < 19; ++i)
	{
		salt[i] = charset[rand() % (sizeof(charset) - 1)];
	}
}

void *threadFunc(void *arg)
{
	threadPool_t *pthreadPool = (threadPool_t *)arg;
	pthread_mutex_lock(&pthreadPool->taskQueue.mutex);
	// 从配置文件中读取出连接数据库所需的数据
	char mysql_user[100] = {0};
	getparameter("mysql_user", mysql_user); // getparameter.c
	// printf("mysql_user: %s\n", mysql_user);
	char mysql_password[100] = {0};
	getparameter("mysql_password", mysql_password); // getparameter.c
	// printf("mysql_password: %s\n", mysql_password);
	char mysql_database[100] = {0};
	getparameter("mysql_database", mysql_database); // getparameter.c
	// printf("mysql_database: %s\n", mysql_database);

	MYSQL *mysql = mysql_init(NULL);
	MYSQL *ret = mysql_real_connect(
		mysql,
		"localhost",
		mysql_user,
		mysql_password,
		mysql_database,
		0, NULL, 0);
	if (ret == NULL)
	{
		fprintf(stderr, "mysql_real_connect:%s\n", mysql_error(mysql));
	}
	pthread_mutex_unlock(&pthreadPool->taskQueue.mutex);

	while (1)
	{
		pthread_mutex_lock(&pthreadPool->taskQueue.mutex);
		while (pthreadPool->taskQueue.size <= 0)
		{
			pthread_cond_wait(&pthreadPool->taskQueue.cond, &pthreadPool->taskQueue.mutex);
		}
		int netfd = pthreadPool->taskQueue.front->net_fd;
		deQueue(&pthreadPool->taskQueue);
		pthread_mutex_unlock(&pthreadPool->taskQueue.mutex);

		train_t train;
		bzero(&train, sizeof(train));

		char opt[2] = {0};
		char username[1024] = {0};
		char password[1024] = {0};
		// 注册or登录
		recv(netfd, &train.length, sizeof(train.length), 0);
		if (train.length == 0)
		{
			close(netfd);
			break;
		}
		recv(netfd, train.data, train.length, MSG_WAITALL);
		memcpy(opt, train.data, train.length);
		if (opt[0] == '1') // 注册
		{
			while (1)
			{
				// 接收客户端传输过来的用户名和密码
				bzero(&train, sizeof(train));
				bzero(username, sizeof(username));
				bzero(password, sizeof(password));
				recv(netfd, &train.length, sizeof(train.length), 0);
				recv(netfd, train.data, train.length, MSG_WAITALL);
				memcpy(username, train.data, train.length);
				bzero(&train, sizeof(train));
				recv(netfd, &train.length, sizeof(train.length), 0);
				recv(netfd, train.data, train.length, MSG_WAITALL);
				memcpy(password, train.data, train.length);

				char sql[4096] = {0};
				char salt[1024] = {0};
				generate_salt(salt, 19);
				char cryptpassword[1024] = {0};
				strcpy(cryptpassword, crypt(password, salt));
				sprintf(sql, "insert into user_info (username,salt,cryptpassword,current_path) values ('%s','%s','%s','%s');", username, salt, cryptpassword, "/");
				puts(sql);
				int qret1 = mysql_query(mysql, sql);
				/* fprintf(stderr, "Insert error %d: %s\n", mysql_errno(mysql), mysql_error(mysql));
				printf("mysql_query的执行结果：%d\n", qret); */

				bzero(&sql, sizeof(sql));
				sprintf(sql, "insert into all_user_file (filename,username,parent_id,file_path,file_type) values ('%s','%s','%d','%s','%s');", "/", username, -1, "/", "Directory");
				puts(sql);
				int qret2 = mysql_query(mysql, sql);
				if (qret1 != 0 || qret2 != 0)
				{
					bzero(&train, sizeof(train));
					train.length = strlen("register_fail");
					strcpy(train.data, "register_fail");
					send(netfd, &train, sizeof(train.length) + train.length, MSG_NOSIGNAL);
				}
				else
				{
					bzero(&train, sizeof(train));
					train.length = strlen("register_success");
					strcpy(train.data, "register_success");
					send(netfd, &train, sizeof(train.length) + train.length, MSG_NOSIGNAL);
					break;
				}
			}
		}

		if (opt[0] == '2') // 登录
		{
			while (1)
			{
				bzero(&train, sizeof(train));
				bzero(username, sizeof(username));
				bzero(password, sizeof(password));
				recv(netfd, &train.length, sizeof(train.length), MSG_WAITALL);
				if (train.length == 0)
				{
					close(netfd);
					break;
				}
				recv(netfd, train.data, train.length, MSG_WAITALL);
				memcpy(username, train.data, train.length);

				bzero(&train, sizeof(train));
				recv(netfd, &train.length, sizeof(train.length), MSG_WAITALL);
				recv(netfd, train.data, train.length, MSG_WAITALL);
				memcpy(password, train.data, train.length);

				char sql[4096] = {0};
				sprintf(sql, "select * from user_info where username = '%s';", username);
				puts(sql);
				int qret = mysql_query(mysql, sql);
				if (qret != 0)
				{
					fprintf(stderr, "mysql_query:%s\n", mysql_error(mysql));
				}
				MYSQL_RES *res = mysql_store_result(mysql);
				if (res == NULL)
				{
					train.length = strlen("not_exist");
					strcpy(train.data, "not_exist");
					send(netfd, &train, sizeof(train.length) + train.length, MSG_NOSIGNAL);
					mysql_free_result(res);
					break;
				}
				MYSQL_ROW row = mysql_fetch_row(res);
				if (row == NULL)
				{
					train.length = strlen("not_exist");
					strcpy(train.data, "not_exist");
					send(netfd, &train, sizeof(train.length) + train.length, MSG_NOSIGNAL);
					mysql_free_result(res);
					break;
				}
				char *cryptpassword = crypt(password, row[2]);
				if (!strcmp(row[1], username) && !strcmp(row[3], cryptpassword))
				{
					char sql[1024] = {0};
					sprintf(sql, "update user_info set current_path = '/' where username = '%s';", username);
					int qret = mysql_query(mysql, sql);
					if (qret != 0)
					{
						fprintf(stderr, "mysql_query:%s\n", mysql_error(mysql));
						return 0;
					}
					puts(sql);

					train.length = strlen("login_success");
					strcpy(train.data, "login_success");
					send(netfd, &train, sizeof(train.length) + train.length, MSG_NOSIGNAL);
					mysql_free_result(res);
					printf("用户%s登录成功！\n", username);
					break;
				}
				else
				{
					train.length = strlen("login_fail");
					strcpy(train.data, "login_fail");
					send(netfd, &train, sizeof(train.length) + train.length, MSG_NOSIGNAL);
					mysql_free_result(res);
				}
			}
		}
		handle(netfd, username, mysql); // 子线程执行任务
	}
	mysql_close(mysql);
	return NULL;
}